package com.xxl.job.executor.service.jobhandler;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.bizsys.domain.LoanOrder;
import com.ruoyi.bizsys.service.ILoanOrderService;
import com.ruoyi.business.service.ILoanService;
import com.ruoyi.common.enums.RspEnmu;
import com.ruoyi.common.exception.BusinessException;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.List;

import static com.ruoyi.bizsys.utils.BizConstants.BIZ_STATUS_1;

/**
 * 放款交易结果查询任务
 *
 * @author Jamnsin
 */
@Slf4j
@Component
public class LoanTransferQueryJob {

    @Autowired
    ILoanOrderService loanOrderService;

    @Autowired
    ILoanService loanService;

    @XxlJob("loanTransferQueryJobHandler")
    public void execute() {
        XxlJobHelper.log("放款交易结果轮询任务 Start >>>>>>>>>>");

        List<LoanOrder> loanOrderPendingList = loanOrderService.list(
                new QueryWrapper<LoanOrder>()
                        .select("id", "cust_no", "loan_serial_no", "loan_amt", "freeze_date", "pay_trans_serial_no")
                        .eq("loan_status", LoanOrder.LOAN_STATUS_3_LOAN_PENDING).eq("state", BIZ_STATUS_1));
        if (CollectionUtils.isEmpty(loanOrderPendingList)) {
            XxlJobHelper.log(" 放款交易结果轮询任务 End >>>>>>>>>> 无待处理数据");
            return;
        }

        XxlJobHelper.log("放款中的待处理数据为：{} 条", loanOrderPendingList.size());

        loanOrderPendingList.stream().forEach(p -> {
            try {
                loanService.verifyTransfer(p, false);
            } catch (Exception e) {
                if (e instanceof BusinessException) {
                    BusinessException be = (BusinessException) e;
                    if (RspEnmu.LOAN_PENDING.getCode().equals(be.getCode())) {
                        return;
                    }
                }
                XxlJobHelper.log("查询客户{} - {} 交易结果异常：", p.getCustNo(), p.getPayTransSerialNo());
                XxlJobHelper.log(e);
            }
        });

        XxlJobHelper.log("放款交易结果轮询任务 End >>>>>>>>>>");
    }
}
